// Tiler.cs created with MonoDevelop
// User: jknight at 11:19 AM 3/4/2009
//
// To change standard headers go to Edit->Preferences->Coding->Standard Headers
//

using System;
using System.Collections.Generic;
using Gtk;
using System.IO;
using System.Diagnostics;
using System.Threading;

namespace com.rootsilver{

	public partial class Tiler : Gtk.Window
	{
		const int COL_PATH = 0;
		const int COL_DISPLAY_NAME = 1;
		const int COL_PIXBUF = 2;
		const int COL_IS_DIRECTORY = 3;

		private int zoomLevel = 100;
		private int zoomIncrement = 100;
		private IconView iconView;
		private ListStore store;
		private ScrolledWindow sw;
		
		private String tempDir = "/tmp/.imagetiler";
		
		public Tiler(string filePath) : base(Gtk.WindowType.Toplevel)
		{
			if(!Directory.Exists(tempDir)) Directory.CreateDirectory(tempDir);
			
			this.Build(); 
			
			SetDefaultSize(650, 400);
					                                                          
			ToolButton convertButton = new ToolButton (Stock.Convert);	
			convertButton.IsImportant = true;
			
			sw = new ScrolledWindow();
 
			sw.ShadowType = ShadowType.EtchedIn;
			
			sw.SetPolicy (PolicyType.Automatic, PolicyType.Automatic);
			this.vbox1.PackStart (sw, true, true, 0);

			if(! string.IsNullOrEmpty(filePath) ){
				this.filechooserbutton2.SetFilename(filePath);
				this.FillStore();
			}else{
				this.filechooserbutton2.SetCurrentFolder("/home/jknight/BJJ/640x480/files/");
			}
			
			this.FillStore();
			
			ShowAll ();
		}

		
		Gdk.Pixbuf GetIcon (string filePath)
		{
			Gdk.Pixbuf pixBuf = new Gdk.Pixbuf(filePath, this.zoomLevel, this.zoomLevel, true);
			
			return pixBuf;
		}

		ListStore CreateStore ()
		{
			// path, name, pixbuf, is_dir
			ListStore store = new ListStore(typeof (string), typeof (string), typeof(Gdk.Pixbuf), typeof (bool));
	
			return store;
		}

		void FillStore()
		{
			this.sw.Remove(this.iconView);
				
			// Create the store and fill it with the contents of '/'
			this.store = CreateStore ();
			//FillStore ();
			
			string[] files = Directory.GetFiles(this.tempDir);
			
			int i = 1;
			foreach(string file in files){
				this.store.AppendValues(file, "", GetIcon(file), true);
				++i;
			}
			
			this.iconView = new IconView(store);
			this.iconView.Spacing = 0;
			this.iconView.KeyPressEvent += new KeyPressEventHandler(OnKeyPressed);

			this.iconView.SelectionMode = SelectionMode.Multiple;

			this.iconView.TextColumn = COL_DISPLAY_NAME;
			this.iconView.PixbufColumn = COL_PIXBUF;
			
			this.sw.Add(this.iconView);
			
			this.ShowAll();
		}
		
		
		void OnKeyPressed(object sender, KeyPressEventArgs args){
			
			if(args.Event.Key == Gdk.Key.Delete
			                 ||
			   args.Event.Key == Gdk.Key.BackSpace)
			{
				IconView view = (IconView)sender;
				
				foreach(TreePath treePath in view.SelectedItems){
					
					TreeIter iter;
					
					store.GetIter(out iter, treePath);
					
					string path = (string)store.GetValue(iter, COL_PATH);
					
					this.Delete(path);
					
				}
				
				
				this.FillStore();
			}
		}
		
		public void Delete(String path){
			File.Delete(path);
			

		}
		

		void OnWinDelete (object sender, DeleteEventArgs a)
		{
			Application.Quit ();
			a.RetVal = true;
		}

		protected virtual void OnExtractFramesButtonClicked (object sender, System.EventArgs e)
		{
			
			if(Directory.Exists(this.tempDir)) 
				Directory.Delete(this.tempDir, true);

			Directory.CreateDirectory(this.tempDir);
			
			string moviePath = this.filechooserbutton2.Filename;
			
			ProcessStartInfo processStartInfo = new ProcessStartInfo();
			
			processStartInfo.UseShellExecute = false;			
			processStartInfo.RedirectStandardOutput = true;
			processStartInfo.RedirectStandardError = true;
			processStartInfo.FileName = "ffmpeg";
			processStartInfo.Arguments = " -s 320x240 -sameq -i \"" + moviePath + "\" -ss " + this.ssEntry.Text + " -t " + this.tEntry.Text + " -r " + this.rButton.Text + " -f image2 " + this.tempDir + "/%03d.jpg";
			
			Process process = new Process(); //Process.Start();
								
			process.Exited += new EventHandler(this.ProcessExited);
			process.EnableRaisingEvents = true;
			process.StartInfo = processStartInfo;
			process.Start();
			
			process.WaitForExit();
			
			this.FillStore();
		
		}
		
		protected virtual void OnMontageButtonClicked (object sender, System.EventArgs e)
		{
			ProcessStartInfo processStartInfo = new ProcessStartInfo();
			processStartInfo.CreateNoWindow = false;
			
			processStartInfo.FileName = "montage";
			processStartInfo.Arguments = tempDir + "/*.* -border 4  -mode Concatenate -tile " + this.montageWidthButton.Text + "x out.jpg";

			Process process = Process.Start(processStartInfo);
			process.EnableRaisingEvents = true;
			
			process.WaitForExit();
			
			Process.Start("eog out.jpg");
		}
		
		private void ProcessExited(object sender, EventArgs e)
		{
			Process process = (Process)sender;
			StreamReader stderr = process.StandardError;

			string line = null;
			string line2 = null;
			while( ( line = stderr.ReadLine()) != null){
				
				if(line.IndexOf("frame=") != -1){
					line2 = line;
				}
			}
			this.statusLabel.Text = line2;
		}

		protected virtual void zoomInButtonClicked (object sender, System.EventArgs e)
		{
			
			if(this.zoomLevel < 600){
				this.zoomLevel += this.zoomIncrement;
				this.FillStore();
			}
		}

		protected virtual void zoomOutButtonClicked (object sender, System.EventArgs e)
		{
			if(this.zoomLevel > 50){				
				this.zoomLevel -= this.zoomIncrement;
				this.FillStore();
			}
			
		}

		private void VideoPreviewComplete(object sender, EventArgs e)
		{
			Process process = (Process)sender;
			StreamReader stderr = process.StandardError;
			StreamReader stdout = process.StandardOutput;
			Console.WriteLine(stdout.ReadToEnd());
				
			//string line = null;
			//string line2 = null;
			//while( ( line = stdout.ReadLine()) != null){
			//	this.combobox1.Add(new ComboBoxEntry(new string[]{line}));	
			//}
			 
		}
		protected virtual void playButtonClicked (object sender, System.EventArgs e)
		{
			ProcessStartInfo info = new ProcessStartInfo();
			info.FileName = "gnome-terminal";
			info.RedirectStandardError = true;
			info.RedirectStandardOutput = true;
			info.UseShellExecute = false;
			info.Arguments = " -x mplayer \"" + this.filechooserbutton2.Filename + "\"";
			
			Process process = new Process();
			process.StartInfo = info;
			process.EnableRaisingEvents = true;
		
			//process.Exited += new EventHandler(VideoPreviewComplete);
			process.OutputDataReceived += new DataReceivedEventHandler(VideoPreviewComplete);
			process.Start();
			process.WaitForExit();
			
		}

		protected virtual void ViewFramesButtonClicked (object sender, System.EventArgs e)
		{
			this.zoomLevel = 640;

			this.Resize(800, this.zoomLevel + 80);
			
			this.FillStore();
		}

		protected virtual void OnSmallButtonClicked (object sender, System.EventArgs e)
		{
			this.zoomLevel = 150;
			
			this.FillStore();
		}
	}
}
